<?php

class Install extends Controller {

	public function run() {
		if (empty($_GET['plugin']) || empty($_GET['ver'])) {
			$this->template('message', array('message' => '参数错误'));
		}

		$plugin = $_GET['plugin'];
		$ver = $_GET['ver'];

		$table = new Sdk\lib\Sql();

		$sql = ROOT_PATH . '/www/' . $plugin . '/' . $ver . '/install/install.sql';
		if (file_exists($sql)) {
			$sql = file_get_contents($sql);
			$table->getCreateData($sql);
			foreach ($table->new as $tableName => $data) {
				$info = $table->checkTable($tableName);
				if (!$info) {
					if (!$table->createTable($tableName, $data['sql'])) {
						$this->errorMessage('install fail');
					}
				} else {
					$update = $table->compareCols($tableName);
					foreach ($update as $sql) {
						if (!$table->alterTable($tableName, $sql)) {
							$this->errorMessage('install fail');
						}
					}
				}
			}
		}

		$sql = ROOT_PATH . '/www/' . $plugin . '/' . $ver . '/install/data.sql';
		if (file_exists($sql)) {
			$conf = Sdk\lib\Config::GetRoot();
			$sql = file_get_contents($sql);
			$v = $conf['dataVer'][$plugin . '_' . $ver] ?? 0;
			list($sql, $lastVer) = $table->getCurrentSql($sql, $v);
			$table->runSqls($sql);
			if ($v != $lastVer) {
				$conf['dataVer'][$plugin . '_' . $ver] = $lastVer;
				\Sdk\lib\Config::SetRoot($conf);
			}
		}

		$this->template('message', array('message' => '本地应用已安装更新完成'));
	}

}